package com.microcm.system.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.lucene.document.Document;
import org.apache.lucene.index.Term;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.ScoreDoc;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.search.TopDocs;

import com.microcm.common.CFUtils;
import com.microcm.common.CUtils;
import com.microcm.common.Final;
import com.microcm.common.SystemToolkit;

public class ClickServlet extends HttpServlet
{
	private static final long serialVersionUID = 1L;

	@Override
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
	{
		// 获得链接
		String clickUrl = req.getQueryString();
		clickUrl = CFUtils.urlDecode(clickUrl);
		clickUrl = CFUtils.urlDecode(clickUrl);

		// 用户的编号
		String unid = null;

		// 请求的域名
		String queryDomain = req.getServerName();

		// 获得索引器
		IndexSearcher searcher = SystemToolkit.getIndexSearcher(Final.INDEX_USER);
		if (searcher != null)
		{
			// 查询条件
			Query query = new TermQuery(new Term("domain", queryDomain));
			TopDocs topDocs = searcher.search(query, 1);
			// 是否只查询出一条是对的
			if (topDocs.totalHits == 1)
			{
				// 搜索返回的结果集合
				ScoreDoc[] hitDocs = topDocs.scoreDocs;
				Document doc = searcher.doc(hitDocs[0].doc);
				unid = doc.get("unid");
			}
			searcher.close();
		}
		// 如果没有
		if (CUtils.isEmpty(unid))
		{
			unid = Final.UNID_DEFAULT;
		}

		// 替换
		clickUrl = CUtils.setParamToUrl(clickUrl, "unid", unid);

		// 跳转
		resp.sendRedirect(clickUrl);
	}

}
